<!--
 * @Description: 部门信息MODAL
 * @Version: 2.0
 * @Autor: 许国辉
 * @Date: 2022-12-13 13:00:56
 * @LastEditors: 许国辉
 * @LastEditTime: 2023-05-13 15:40:54
-->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './tableDepData';
  import {
    getDepartmentListResultModel,
    updateDepartmentListResultModel,
  } from '/@/api/baseInfo/departmentInfoAPI';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
        autoFocusFirstItem: true,
        compact: true,
        size: 'small',
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

        const treeData = await getDepartmentListResultModel(data.record);
        // console.log(treeData);

        updateSchema({
          field: 'parentDept',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api

          if (typeof values.allDepartName === 'object') {
            values.allDepartName = values.allDepartName.join('');
          } else if (values.allDepartName === undefined) {
            values.allDepartName = '';
          }
          values.updatetime = new Date().getTime();
          values.operatorid = useUserStore().getUserInfo.id;
          await updateDepartmentListResultModel(values)
            .then((res) => {
              console.log(res);
            })
            .catch((err) => {
              console.log(err);
            });

          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
